import { axios } from 'taro-axios'
import Taro from '@tarojs/taro';

// 公共提示
const shwoErrorToast = (msg: any) => {
  Taro.showToast({
    title: msg,
    icon: 'none'
  })
}

// 请求根路径
const instance = axios.create({
  baseURL: process.env.TARO_APP_HOST_API,
})

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // Taro.showLoading({
    //   title: '加载中',
    //   mask: true //使用蒙层
    // })
    let token = Taro.getStorageSync('token')
    if (typeof token == undefined) {
      token = '';
    }
    config.headers = {
      'Content-Type': 'application/json;charset=utf-8',
      Authorization: token,
    }
    return config;
  }, (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (response: any) => {
    Taro.hideLoading()
    if (response.data.isError) {
      shwoErrorToast(response.data.error.message)
    } else {
      return response.data;
    }
  }, (error) => {
    if (error.response) {
      Taro.hideLoading()
      console.log('err', error)

      let res = error.response.data
      switch (res.code) {
        case 400:
          shwoErrorToast(res.message || '非法请求')
          break
        case 401:
          shwoErrorToast('登录过期')// 可以尝试无感登陆或者跳转到登陆页
          break
        case 403:
          shwoErrorToast(res.message || '非法请求')
          break
        case 404:
          shwoErrorToast(res.message || '非法请求')
          break
        case 500:
        case 502:
          shwoErrorToast(res.message || '服务器开小差啦')
          break
        default:
          shwoErrorToast(res.msg || '服务器异常，请重试')
      }
    } else {
      console.log(error)
      shwoErrorToast('请检查网络连接状态')
    }
    return Promise.reject(error)
  }
)

export default instance